package com.solution.admin.quartz;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.solution.common.redis.RedisCacheClient;
import com.solution.wx.share.entity.ShareCommentEntity;
import com.solution.wx.share.entity.ShareInfoEntity;
import com.solution.wx.share.entity.ShareInteractionCountEntity;
import com.solution.wx.share.service.ShareCommentService;
import com.solution.wx.share.service.ShareInfoService;
import com.solution.wx.share.service.ShareInteractionCountService;

/**
 * 分享数据同步定时任务
 * @author xkl
 * @date 2018年5月22日 上午9:05:05
 */
public class ShareInteractionTimeTask {

	@Autowired
	private ShareInfoService shareInfoService;
	
	@Autowired
	private ShareCommentService shareCommentService;
	
	@Autowired
	private ShareInteractionCountService shareInteractionCountService;
	
	@Autowired
	RedisCacheClient redisCacheClient;
	
	public void execute(){
		try {
			List<String> changeIdList = shareInfoService.listChangeShareInfo();
			List<ShareInteractionCountEntity> interactionList = new ArrayList<ShareInteractionCountEntity>();
			List<ShareCommentEntity> shareCommentList = new ArrayList<ShareCommentEntity>();
			for (String changeId : changeIdList) {
				if (changeId.indexOf("COMMENT_") > -1) {
					//评论点赞
					ShareCommentEntity comment = new ShareCommentEntity();
					Long commentId = Long.parseLong(changeId.split("_")[1]);
					Long commentLikeQuantity = shareCommentService.getShareCommentLikeQuantity(commentId);
					comment.setId(commentId);
					comment.setCommentLikeQuantity(commentLikeQuantity);
					shareCommentList.add(comment);
				} else {
					//分享交互数据
					ShareInteractionCountEntity entity = new ShareInteractionCountEntity();
					ShareInfoEntity shareInfo = shareInfoService.getShareInteraction(changeId);
					entity.setId(Long.parseLong(changeId));
					entity.setShareLikeQuantity(shareInfo.getLikeQuantity());
					entity.setShareCommentQuantity(shareInfo.getCommentQuantity());
					entity.setShareQuantity(shareInfo.getShareQuantity());
					entity.setFavoriteQuantity(shareInfo.getFavoriteQuantity());
					entity.setViewQuantity(shareInfo.getViewQuantity());
					entity.setRegisterQuantity(shareInfo.getRegisterQuantity());
					entity.setUvViewQuantity(shareInfo.getUvViewQuantity());
					interactionList.add(entity);
				}
			}
			//将redis中的分享交互数据持久化到数据库中
			if (interactionList.size() != 0) {
				shareInteractionCountService.updateShareInteractionCountBatch(interactionList);
			}
			if (shareCommentList.size() != 0) {
				shareCommentService.updateShareCommentLikeQuantity(shareCommentList);
			}
			//清除redis中的已持久化分享交互数据
			if (changeIdList.size() != 0) {
				shareInfoService.removeShareInteractionChange(changeIdList);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
